package org.jsola.hr.common;

import com.baidu.aip.ocr.AipOcr;
import lombok.extern.slf4j.Slf4j;
import org.jsola.common.StrKit;
import org.jsola.exception.ParamException;
import org.jsola.hr.exception.HrException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BaiduVerified {

    //设置APPID/AK/SK
    public static final String APP_ID = "19035291";
    public static final String API_KEY = "0k5M8GX2kNM3xtN6mlW7v2Gj";
    public static final String SECRET_KEY = "6Yb6qjYHt3Go5Ebcwu7RzZCl4rxDnpyW";

    /**
     * 身份证含照片的一面
     */
    public static final String ID_CARD_SIDE_FRONT = "front";
    /**
     * 身份证带国徽的一面
     */
    public static final String ID_CARD_SIDE_BACK = "back";

    public static void main(String[] args) throws IOException {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 可选：设置代理服务器地址, http和socket二选一，或者均不设
        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        String netUrl = "https://res.huaerk.com/local/8aab561a-f308-4ffe-866c-10b472225432.jpg";

    }

    public static Map<String, String> sample(String netUrl, String inputIdCard) {
        return sample(netUrl, inputIdCard, ID_CARD_SIDE_FRONT);
    }

    public static Map<String, String> sample(String netUrl, String inputIdCard, String idCardSide) {

        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 返回的识别姓名跟身份证号
        Map<String, String> resultMap = new HashMap<>();
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");
        if (StrKit.isEmpty(idCardSide)) {
            idCardSide = ID_CARD_SIDE_FRONT;
        }
        // 参数为本地图片路径
//        String image = "C:\\Users\\chenyonglei\\Pictures\\Camera Roll\\微信图片_20200320133653.jpg";
//        String image = getFilePath(netUrl);

        JSONObject res = client.idcard(netUrl, idCardSide, options);
        log.info("百度实名认证:idcard:{},返回信息:{}", inputIdCard, res.toString());
        Map<String, Object> result = res.toMap();
        if (result == null || result.size() == 0 || result.get("image_status") == null) {
            throw new ParamException("调用第三方实名认证失败,请联系管理员");
        }
        if (ID_CARD_SIDE_FRONT.equals(idCardSide)) {
            log.info("百度实名认证:身份证人像面");
            String imageStatus = result.get("image_status").toString();
            if ("normal".equals(imageStatus)) {
                // 校验身份证识别信息
                String typeNum = result.get("idcard_number_type").toString();
                if ("-1".equals(typeNum)) {
                    throw new ParamException("身份证正面所有字段全为空");
                } else if ("0".equals(typeNum)) {
                    throw new ParamException("身份证证号识别错误");
                } else if ("1".equals(typeNum)) {
                    log.info("身份证证号和性别、出生信息一致");
                } else if ("2".equals(typeNum)) {
                    throw new HrException("身份证证号和性别、出生信息都不一致");
                } else if ("3".equals(typeNum)) {
                    throw new ParamException("身份证证号和出生信息不一致");
                } else if ("4".equals(typeNum)) {
                    throw new ParamException("身份证证号和性别信息不一致");
                }
                Map<String, Object> idCard = (Map<String, Object>) result.get("words_result");
                Map<String, Object> nameMap = (Map<String, Object>) idCard.get("姓名");
                Map<String, Object> cardMap = (Map<String, Object>) idCard.get("公民身份号码");
                Map<String, Object> nationMap = (Map<String, Object>) idCard.get("民族");
                Map<String, Object> addressMap = (Map<String, Object>) idCard.get("住址");
                Map<String, Object> birthdayMap = (Map<String, Object>) idCard.get("出生");
                Map<String, Object> sexMap = (Map<String, Object>) idCard.get("性别");
                String name = nameMap.get("words").toString();
                String idcard = cardMap.get("words").toString();
                String nation = nationMap.get("words").toString();
                String address = addressMap.get("words").toString();
                String birthday = birthdayMap.get("words").toString();
                String sex = sexMap.get("words").toString();
                log.info(name + "----" + idcard);
                resultMap.put("name", name);
                resultMap.put("idcard", idcard);
                resultMap.put("nation", nation);
                resultMap.put("address", address);
                resultMap.put("birthday", birthday);
                resultMap.put("sex", sex);
            } else if ("reversed_side".equals(imageStatus)) {
                throw new ParamException("身份证正反面颠倒");
            } else if ("non_idcard".equals(imageStatus)) {
                throw new ParamException("上传的图片中不包含身份证");
            } else if ("blurred".equals(imageStatus)) {
                throw new ParamException("身份证模糊");
            } else if ("other_type_card".equals(imageStatus)) {
                throw new ParamException("其他类型证照");
            } else if ("over_exposure".equals(imageStatus)) {
                throw new ParamException("身份证关键字段反光或过曝");
            } else if ("over_dark".equals(imageStatus)) {
                throw new ParamException("身份证欠曝（亮度过低）");
            } else if ("unknown".equals(imageStatus)) {
                throw new ParamException("身份证识别失败：未知错误，请重新拍照上传");
            } else {
                log.error("百度实名认证失败:idcard:{},返回信息:{}", inputIdCard, res.toString());
                throw new ParamException("调用实名认证服务器失败");
            }
        } else {
            log.info("百度实名认证:身份证国徽面");
            Map<String, Object> idCard = (Map<String, Object>) result.get("words_result");
            Map<String, Object> issuedByMap = (Map<String, Object>) idCard.get("签发机关");
            Map<String, Object> cardStartDateMap = (Map<String, Object>) idCard.get("签发日期");
            Map<String, Object> cardEndDateMap = (Map<String, Object>) idCard.get("失效日期");
            String issuedBy = issuedByMap.get("words").toString();
            String cardStartDate = cardStartDateMap.get("words").toString();
            String cardEndDate = cardEndDateMap.get("words").toString();
            resultMap.put("issuedBy", issuedBy);
            resultMap.put("cardStartDate", cardStartDate);
            resultMap.put("cardEndDate", cardEndDate);
        }
        return resultMap;
    }
}
